class CategorsController < ApplicationController
  include ControllerHelper
  before_filter :init, :only => :index
  before_filter :require_admin, :except => :index

  def index
    @categors = Categor.joins(:shop).where("categors.status = 'approved' and shops.time IN (?) and shops.id = ?", ["round", @time], params[:shop_id])
    @shop = Shop.where("status = 'approved' and id = ?", params[:shop_id]).first
  end

  def new
    set_form_settings
    @page["name"] = "categor"
    @categor = Categor.new
    render :layout => "form"
  end

  def create
    begin
      @categor = Categor.new(params[:categor])
      if @categor.save
        redirect_to categor_admin_path(:status => "all") and return
      else
        set_form_settings
        @page["name"] = "categor"
        render :action => "new", :layout => "form"
      end
    rescue
      flash[:notice] = I18n.t "site.message.corrupted_html"
      set_form_settings
      @page["name"] = "categor"
      render :action => "new", :layout => "form"
    end
  end

  def admin
    per_page = params[:per_page] ||= @site["per_page"]["admin"]["categors"]
    conditions = []
    conditions = merge_conditions(conditions, ["status = ?", "approved"]) if params[:status] == "approved"
    conditions = merge_conditions(conditions, ["status <> ?", "approved"]) if params[:status] == "banned"
    @categors = Categor.find(:all, :conditions => conditions, :order => :shop_id).uniq.paginate(:page => params[:page], :per_page => per_page)
    set_admin_settings
    render :layout => "cms"
  end

  def destroy
    @categor = Categor.find(:first, :conditions => ["id = ?", params[:id]])
    if @categor
      @categor.destroy
    else
      flash[:notice] = I18n.t "site.message.no_categor"
    end
    redirect_to categor_admin_path(:status => "all")
  end

  def edit
    set_form_settings
    @page["name"] = "categor"
    @categor = Categor.find(:first, :conditions => ["id = ?", params[:id]])
    if @categor.nil?
      flash[:notice] = I18n.t "site.message.no_categor"
      redirect_to categor_admin_path(:status => "all") and return
    else
      render :layout => "form"
    end
  end

  def update
    @categor = Categor.find(:first, :conditions => ["id = ?", params[:id]])
    if @categor.nil?
      flash[:notice] = I18n.t "site.message.no_categor"
      redirect_to categor_admin_path(:status => "all") and return
    else
      if @categor.update_attributes(params[:categor])
        redirect_to categor_admin_path(:status => "all") and return
      else
        set_form_settings
        @page["name"] = "categor"
        render :layout => "form", :action => "edit", :id => params[:id]
      end
    end
  end

  def approve_ban
    categor = Categor.find(params[:id])
    old_status = categor.status == "approved" ? "approved" : "banned"
    categor.status = categor.status == "approved" ? "banned" : "approved"
    categor.save
    redirect_to categor_admin_path(:status => old_status)
  end

end
